package servlet;

import pojo.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

@WebServlet(urlPatterns = {"/user"})//跟在浏览器地址的最后面
public class UserServlet extends HttpServlet {

   protected void doGet(HttpServletRequest req, HttpServletResponse resp)
           throws ServletException, IOException {
       doPost(req,resp);

   }

   protected void doPost(HttpServletRequest req, HttpServletResponse resp)
           throws ServletException, IOException {

       //来个集合
       List<User> users = new ArrayList<>();
       //jdbc操作数据库   查询
       try {
           Class.forName("com.mysql.cj.jdbc.Driver");

           //2、获取连接
           Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/jdbc?characterEncoding=utf-8",
                   "root","2333");

           if (conn!=null){
               System.out.println("连接成功");
           }

           //3、编写sql语句
           String sql = "select * from sys_user";

           //4、预处理sql  .var
           PreparedStatement preparedStatement = conn.prepareStatement(sql);

           //5、如果有参数，设置参数

           //6、执行sql语句
           ResultSet resultSet = preparedStatement.executeQuery();

           // 7、如果是查询就遍历结果/如果是增删改 判断是否成功
           while (resultSet.next()) {
               User user = new User();
               user.setId(resultSet.getInt(1));
               user.setName(resultSet.getString(2));
               user.setPass(resultSet.getString(3));
               //把对象添加道集合中
               users.add(user);
           }

           //8.关闭资源
           resultSet.close();
           preparedStatement.close();
           conn.close();

           //把集合中数据存储带作用域中
           req.setAttribute("users",users);
           //打开页面
           req.getRequestDispatcher("/user.jsp").forward(req,resp);


       } catch (ClassNotFoundException e) {
           throw new RuntimeException(e);
       } catch (SQLException e) {
           throw new RuntimeException(e);
       }

   }

   }
